var nodemailer = require('nodemailer')
let { TRANSPORTER } = require('./config')

function sendEmail(mailOptions) {

    let transporter = nodemailer.createTransport(TRANSPORTER)

    transporter.sendMail(mailOptions, (err, data) => {
        if (err) {
            // 打印日志
            console.log(err);
        } else {
            console.log(data);
        }
    })
}

/**
 * 
 * @param {String} from 发送方 
 * @param {String} to 接收方 
 * @param {String} subject 邮件标题 
 * @param {Number} type 使用模板类型 
 * @param {Object} options 模板参数对象 
 */

/**
 * options
 * article_title:
 * comment:
 * add_time:
 * website:
 * nickname:
 * reply_nickname: null || nickname
 * reply_email: null || email
 */

function createTemplate(options) {

    let templates = [
        {
            type: 1,
            name: "评论文章",
            template: `<div>
                        <p>#Re:${options.article_title}</p>
                        <br>
                        <br>
                        <p>${options.comment}</p>
                        <hr>
                        <p>评论者: <a href="${options.website}">${options.nickname}</a></p>
                        <p>URL: <a href="${options.website}">${options.website}</a></p>
                    </div>`
        },
        {
            type: 2,
            name: "回复",
            template: `<div>
                        <p>#Re:${options.article_title}</p>
                        <br>
                        <br>
                        <p>@${options.reply_nickname}</p>
                        <p>${options.comment}</p>
                        <hr>
                        <p>评论者: <a href="${options.website}">${options.nickname}</a></p>
                        <p>URL: <a href="${options.website}">${options.website}</a></p>
                    </div>`
        }
    ]

    // 模板类型
    let type = options.reply_email ? 2 : 1,
        // 发送邮箱 
        from = "rinvay2021@163.com",
        // 接收邮箱
        to = options.reply_email || "rinvay1999@163.com",
        // 邮件标题
        subject = "[rinvay博客系统通知]#Re:" + options.article_title

    let [html] = templates.filter(item => item.type == type)

    // console.log(html);

    let mailOptions = {
        from,
        to,
        subject,
        html: html.template
    }
    sendEmail(mailOptions)
}

module.exports = createTemplate